//    This file is part of Open WordSearch.
//
//    Open WordSearch is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Open WordSearch is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Open WordSearch.  If not, see <http://www.gnu.org/licenses/>.
//
//        Copyright 2009, 2010 Brendan Dahl <dahl.brendan@brendandahl.com>
//              http://www.brendandahl.com

package com.abhipedro.wordsearch.view;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.Point;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.abhipedro.wordsearch.util.Constants;
import com.abhipedro.wordsearch.util.ConversionUtil;
import com.abhipedro.wordsearch.view.controller.TextViewGridController;
import com.abhipedro.wordsearch.view.controller.WordSearchActivityController;
import com.abhipedro.wordsearch.view.runnables.HighScoresShow;

/**
 * Activity for the word search game itself
 */
public class WordSearchActivity extends Activity {

	private WordSearchActivityController control;

	private  final int STOPSPLASH = 0;
	private  final long SPLASHTIME = 1000;
	private ProgressDialog progressDialog;
	
	private WebView mWebAdView;
	
	private TextView mWordsLeftView,  mWordBox;
	
	private Typeface mLettersFont ; 	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		progressDialog = ProgressDialog.show(WordSearchActivity.this, "", 
                "Loading. Please wait...", true);
		progressDialog.setCancelable(true);
		progressDialog.show();
		
		mHandler =  new Handler(){
            public void handleMessage(Message msg) {
				if (msg.arg1 == 0)
					progressDialog.show();
				else
					progressDialog.hide();
            }
           };

		setContentView(R.layout.activity_main);
		
		mWebAdView = (WebView) findViewById(R.id.ads);
		WebSettings wbsettings = mWebAdView.getSettings();
		wbsettings.setJavaScriptCanOpenWindowsAutomatically(true);
		wbsettings.setJavaScriptEnabled(true);
		wbsettings.setAllowFileAccess(true);
		wbsettings.setDomStorageEnabled(true);
		wbsettings.setPluginsEnabled(true);

		applyTheme();
		
		
		mLettersFont = Typeface.createFromAsset(getAssets(),	Constants.COMIC_FONT);
		
		// Typeface infoTf =Typeface.createFromAsset(getAssets(),Constants.INFO_FONT);

		mWordsLeftView = (TextView) findViewById(R.id.wordsLeft);
		mWordBox = (TextView) findViewById(R.id.wordBox);

		mWordsLeftView.setTypeface(mLettersFont);
		mWordBox.setTypeface(mLettersFont);

		control = new WordSearchActivityController(this);

		if (savedInstanceState == null) {
			control.newWordSearch();
			Message msg = new Message();
			msg.what = STOPSPLASH;
			mHandler.sendMessageDelayed(msg, SPLASHTIME);
		} else {
			control.restoreState(savedInstanceState);
			if (null != progressDialog) {
				if (progressDialog.isShowing())
					progressDialog.dismiss();
			}
		}
		
		
	}
	
	private void runAd() {
		mWebAdView.loadUrl("file:///android_asset/adspage.html");
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case STOPSPLASH:
				startnewGame();
				progressDialog.dismiss();
			}
			super.handleMessage(msg);
		}
	};

	public void updateLeftWordsCount(final int count) {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				mWordsLeftView.setText("Words Left: " + count);
			}
		});

	}
	

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog;
		switch (id) {
		default:
			dialog = super.onCreateDialog(id);
			break;
		}
		return dialog;
	}

	/** hook into menu button for activity */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		this.getMenuInflater().inflate(R.menu.menu_game, menu);
		menu.findItem(R.id.menu_new).setIcon(android.R.drawable.ic_menu_add);
		menu.findItem(R.id.menu_scores).setIcon(
				android.R.drawable.ic_menu_gallery);
		return super.onCreateOptionsMenu(menu);
	}

	/** when menu button option selected */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_scores:
			HighScoresShow hsShow = new HighScoresShow(control, this, false);
			hsShow.run();
			return true;
		case R.id.menu_new:
			startnewGame();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void startnewGame() {
		control.newWordSearch();
	}

	@Override
	protected void onPause() {
		super.onPause();
		control.timePause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		control.timeResume();
		runAd();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		try {
			control.saveState(outState);
		} catch (Exception e) {
		}
	}

	/**
	 * Change the Theme of the game. This might change the background and/or
	 * letter color
	 */
	public void applyTheme() {
		TextView view = (TextView) this.getLayoutInflater().inflate(R.layout.grid_text_view, null);
		LinearLayout linearback = (LinearLayout) findViewById(R.id.wordsearch_base);
		int themeVal = Integer.valueOf(SettingsActivity.getTheme(this));
		switch (themeVal) {
		case 1: // THEME 1 - Blue/Purple
			linearback.setBackgroundResource(R.drawable.paper_theme);
			view.setTextColor(R.color.black);
			break;
		case 2:// THEME 1 - Blue/Purple
			linearback.setBackgroundResource(R.drawable.background_shelf);
			view.setTextColor(R.color.black);
			break;
		case 3: // THEME 2 - Red
			linearback.setBackgroundResource(R.drawable.background_pink);
			view.setTextColor(R.color.black);
			break;
		case 4:
			linearback.setBackgroundResource(R.drawable.background_purple);
			view.setTextColor(R.color.white);
			break;

		default:
			linearback.setBackgroundResource(R.drawable.background_pink); // LAST
			break;
		}
	}

	/**
	 * creates a grid of textViews from layout files based on the gridSize and
	 * sets the new textViews to use the controller as their listener
	 * @param gridSize   square size of the new grid to make
	 * @param controller  the onkeyListener used for the grid's textViews, also holds
	 *            the gridView an array of the new textView's in the grid
	 */
	public void setupViewGrid(int gridSize, TextViewGridController controller) {
		ViewGroup gridTable = (ViewGroup) this.findViewById(R.id.gridTable);
		gridTable.removeAllViews();
		int portion = gridTable.getHeight() / gridSize;
		gridTable.setKeepScreenOn(true);
		Point point = new Point();
		TextView[][] gridView = controller.getGridView();
		for (point.y = 0; point.y < gridSize; point.y++) {
			ViewGroup row = (ViewGroup) this.getLayoutInflater().inflate(
					R.layout.grid_row, null);
			row.setMinimumHeight(portion);
			TextView[] rowText = new TextView[gridSize];
			for (point.x = 0; point.x < gridSize; point.x++) {
				TextView view = (TextView) this.getLayoutInflater().inflate(R.layout.grid_text_view, null);
				view.setHeight(portion);
				view.setId(ConversionUtil.convertPointToID(point));

				Typeface face = Typeface.createFromAsset(getAssets(), Constants.COMIC_FONT);
				view.setTypeface(face);
				view.setTextSize((float) (Constants.LETTER_BOX_SIZE - gridSize));
				int themeVal = Integer.valueOf(SettingsActivity.getTheme(this));
				switch (themeVal) {
				case 1:
				case 2:
				case 3:
					view.setTextColor(R.color.black);
					break;
				case 4:
					view.setTextColor(R.color.white);
					break;
				}

				rowText[point.x] = view;
				row.addView(view);
			}
			gridView[point.y] = rowText;
			gridTable.addView(row);
			row.requestLayout();
			row.invalidate();
		}
		gridTable.setOnTouchListener(controller);
	}



	public void setHandler(Handler mHandler) {
		this.mHandler = mHandler;
	}


	public Handler getHandler() {
		return mHandler;
	}
	
	

}
